package org.ysling.litemall.core.tasks.impl;
/**
 *  Copyright (c) [ysling] [927069313@qq.com]
 *  [litemall-plus] is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *              http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 *  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 *  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 */

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ysling.litemall.core.service.ActionLogService;
import org.ysling.litemall.core.tasks.service.Task;
import org.ysling.litemall.core.utils.BeanUtil;
import org.ysling.litemall.db.constant.CouponConstant;
import org.ysling.litemall.db.domain.*;
import org.ysling.litemall.db.service.*;

import java.util.Objects;

/**
 * 优惠券过期队列
 */
public class CouponExpiredTask extends Task {

    private final Log logger = LogFactory.getLog(CouponExpiredTask.class);
    private final Integer couponId;

    public CouponExpiredTask(Integer couponId, long delayInMilliseconds){
        super("CouponExpiredTask-" + couponId, delayInMilliseconds);
        this.couponId = couponId;
    }

    @Override
    public void run() {
        logger.info(String.format("系统处理延时任务 -> [开始-优惠券过期] [任务ID-%s]" , this.couponId));

        ActionLogService logService = BeanUtil.getBean(ActionLogService.class);
        LitemallCouponService couponService = BeanUtil.getBean(LitemallCouponService.class);

        LitemallCoupon coupon = couponService.findById(this.couponId);
        if(coupon == null || !Objects.equals(CouponConstant.STATUS_NORMAL , coupon.getStatus())) return;

        coupon.setStatus(CouponConstant.STATUS_EXPIRED);
        if (couponService.updateVersionSelective(coupon) == 0) {
            throw new RuntimeException("优惠券过期设置失败");
        }

        logger.info(String.format("系统处理延时任务 -> [结束-优惠券过期] [任务ID-%s]" , this.couponId));
        logService.logOrderSucceed("系统处理延时任务",String.format("[结束-优惠券过期] [任务ID-%s]" , this.couponId));
    }
}
